<template>
    <div>
        <label :class="isRequired ? 'required':''">{{label}}</label>
        <slot></slot>
        <p v-show="isErrorShow" class="message">{{message}}</p>
    </div>
</template>
<script>
import AsyncValidator from 'async-validator';
export default {
    name:'form-item',
    inject:['form'],
    data(){
        return {
            isErrorShow:false,   //是否显示错误信息
            message:'',          //错误信息
            isRequired:false     //不需要
        }
    },
    props:{
        label:{
            type:String,
            default:''
        },
        prop:{
            type:String,
            default:''
        }
    },
    mounted(){

        //记录最初的值
        this.initVal = this.getVal;

        this.$parent.$emit('form-add',this);
        //获取当前item的校验规则  
        let rules = this.getRules();

        if(rules.length){ //有校验规则
            rules.forEach(rule => {
                if(rule.required !== undefined) this.isRequired = rule.required
            })
        }

        //值  进行校验

        //失去焦点  进行校验
        this.$on('form-blur',this.handleBlur)
        //input改变  进行校验
        this.$on('form-change',this.handleChange)
    },
    methods:{
        //获取规则
        getRules(){
            return this.form.rules[this.prop]
        },
        //进行校验的方法
        validate(trigger,cb){
            //async-validate  进行校验

            //规则筛选
            let rules = this.getFieldRules(trigger);

            console.log("rules",rules);

            let asyncValidator = new AsyncValidator({[this.prop]:rules});  //规则

            let model = {[this.prop]:this.getVal}; //校验的值
            
            //进行校验
            asyncValidator.validate(model,(error) => {
                if(error){
                    this.isErrorShow = true;
                    this.message = error[0].message;
                }else{
                    this.isErrorShow = false;
                    this.message = '';
                }
                if(cb) cb(this.message)
            })

        },
        //重置
        resetVal(){
            this.form.model[this.prop] = this.initVal;
        },

        //规则筛选

        getFieldRules(trigger){ //''
            //当前的校验规则
            let rules = this.getRules();
            if(rules.length){
                return rules.filter(rule => !trigger ||  rule.trigger === trigger);
            }
        },

        handleBlur(){
            //失去焦点 校验
            this.validate('blur');
        },
        handleChange(){
            //改变 校验
            this.validate('change');
        }
    },
    computed:{
        getVal(){
            return this.form.model[this.prop]
        }
    }  
}
</script>

<style lang="scss" scoped>
    .required:before{
        content:'*';
        color:red;
    }
    .message{
        color:red;
    }
</style>